import { ref, reactive, computed } from "vue";
import { changePassword } from "@/api/user";
import { message } from "@/utils/message";
import { type FormInstance, type FormRules } from "element-plus";
export function useUserCenterInfo() {
  const usercenterinfo = computed(() => {
    return JSON.parse(sessionStorage.getItem("user-info"));
  });
  const accout = usercenterinfo.value.userAccount;
  const nik = usercenterinfo.value.userNiChen;
  const cellphone = usercenterinfo.value.userPhone;
  const users = reactive({
    id: usercenterinfo.value.id,
    newpass: "",
    okpassword: ""
  });
  const ruleFormRef = ref<FormInstance>();
  const update = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid: any) => {
      if (valid) {
        // 提交成功
        GetResetPwd();
      } else {
        return false;
      }
    });
  };

  const GetResetPwd = async () => {
    const res = await changePassword(users);
    console.log("ppp" + JSON.stringify(users));
    if (res.isSuccess == true) {
      message("修改密码成功", { type: "error" });
      ruleFormRef.value.resetFields();
    } else {
      message("修改密码失败", { type: "error" });
    }
  };

  const validatePass = (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("密码不能为空"));
    } else if (value !== users.newpass) {
      callback(new Error("两次密码不一致"));
    } else {
      callback();
    }
  };
  const rules = reactive<FormRules>({
    newpass: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      { min: 3, max: 5, message: "长度3到5个字符", trigger: "blur" }
    ],
    okpassword: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      { validator: validatePass, trigger: "blur" }
    ]
  });
  return {
    usercenterinfo,
    users,
    accout,
    nik,
    cellphone,
    ruleFormRef,
    update,
    rules
  };
}
